package org.lds.hotkey.common.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


    public static <T> T fromJson(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (Exception e) {
            return null;
        }
    }

    public static String toJson(Object o) {
        try {
            return mapper.writeValueAsString(o);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> List<T> fromJsonList(String json, Class<T> tClass) {
        CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass);
        try {
            return mapper.readValue(json, listType);
        } catch (IOException e) {
            return null;
        }
    }

}
